/**
 * 编辑多边形
 * 点击操作点移动位置  点击操作线添加点  右键点击点移除点
 * start方法开始编辑  off方法结束编辑
 * @param {Earth} options.earth 渲染容器
 * @param {Array} options.polygon 要编辑的多边形 EX对象
 * 
 * @returns {PolygonEdit} PolygonEdit实例
 */

function PolygonEdit (options) {

    this.earth = options.earth
    this.polygon = options.polygon
    this.color = options.polygon.color
    this.outlineColor = options.polygon.outline.color
    this.points = []
    this.pointsPositions = []
    this.polygonPositions = []
    this.lines = []
    this.editState = false
    this.viewer = this.earth._viewer
    this.polygonPositions_back = []
    this.radian = 180 / Math.PI;

    this.getPoints()
}

// 获取多边形点坐标
PolygonEdit.prototype.getPoints = function () {
    if (this.editState) {
        return
    }
    this.editState = true

    this.polygon.ground = true
    let pointsPositions = []
    this.polygonPositions = [...this.polygon.positions]
    this.polygonPositions_back = [...this.polygon.positions]
    for (let i = 0; i < this.polygonPositions.length / 2; i ++) {
        pointsPositions.push([
            this.polygonPositions[ i * 2 ],
            this.polygonPositions[ i * 2 + 1 ],
            0
        ])
    }

    this.pointsPositions = pointsPositions
    this.setLine()
    this.setPoint()
    
    // this.start()
}

// 绘制操作点
PolygonEdit.prototype.setPoint = function () {
    let viewer = this.viewer
    let radian = this.radian

    this.pointsPositions.forEach((item, index) => {
        let point = viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(radian * item[0], radian * item[1], 1),
            point: {
                pixelSize: 10,
                // 填充色
                color: new Cesium.Color(this.color[0], this.color[1], this.color[2], 1),
                // 是否有边框
                outline: true,
                // 边框颜色
                outlineColor: new Cesium.Color(this.outlineColor[0], this.outlineColor[1], this.outlineColor[2], 1),
                // 边框宽度
                outlineWidth: 3
            },
        });

        point.editType = 'editPoint'
        point.activeIndex = index

        this.points.push(point)
    })
}

// 绘制操作线
PolygonEdit.prototype.setLine = function () {

    let lines = []
    for (let i = 0; i < this.pointsPositions.length; i ++) {

        let polyline = new XE.Obj.Polyline(this.earth);
        polyline.ground = true
        polyline.width = 4
        let startPoint = this.pointsPositions[i]
        let endPoint = this.pointsPositions[i + 1] ? this.pointsPositions[i + 1] : this.pointsPositions[0]
        polyline.material.XbsjColorMaterial.color = [ 1,1,1,1 ]
        polyline.positions = [ startPoint, endPoint ]
        polyline.editType = 'editLine'
        polyline.activeIndex = i
        lines.push(polyline)
    }

    this.lines = lines

}

// 开始编辑
PolygonEdit.prototype.start = function () {
    let that = this
    let earth = this.earth
    let canvasbox = this.earth.czm.viewer.canvas
    this.handler = new Cesium.ScreenSpaceEventHandler(canvasbox);
    let mouseClick = false
    let mouseRightClick = false
    let activeIndex = null

    this.polygon.show = false

    // 鼠标左键事件
    this.handler.setInputAction(function (e) {
        mouseClick = true
        setTimeout(() => {
            mouseClick = false
        }, 200)
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN)

    this.handler.setInputAction(function (e) {
        if (!mouseClick) {
            return
        }

        // 通过平面坐标拾取对应模型
        let picked = earth.czm.viewer.scene.pick(e.position);

        if (picked) {
            // 点击操作点
            if (picked.id.editType == 'editPoint') {
                if (activeIndex === null) {
                    // 设置当前活跃操作点
                    activeIndex = picked.id.activeIndex
                    console.log(activeIndex)
                } else {
                    activeIndex = null
                }
            }
            // 点击操作线
            if (picked.id.editType == 'editLine') {
                let position = that.earth.pickPosition({ x: e.position.x, y: e.position.y });
                let pointPosition = Cesium.Cartesian3.fromDegrees(that.radian * position[0], that.radian * position[1], 1)
                // 添加操作点
                that.addPoint(pointPosition, position, picked.id.activeIndex)
            }
        } else {
            activeIndex = null
        }

    }, Cesium.ScreenSpaceEventType.LEFT_UP)

    // 右键移除一个点
    this.handler.setInputAction(function (e) {
        mouseRightClick = true
        setTimeout(() => {
            mouseRightClick = false
        }, 200)
    }, Cesium.ScreenSpaceEventType.RIGHT_DOWN)

    this.handler.setInputAction(function (e) {
        if (!mouseRightClick) {
            return
        }
        // 通过平面坐标拾取对应模型
        let picked = earth.czm.viewer.scene.pick(e.position);

        if (picked) {
            // 点击操作点
            if (picked.id.editType == 'editPoint') {
                let index = picked.id.activeIndex
                // 删除点
                that.viewer.entities.remove(picked.id)
                that.points.splice(index, 1)
                // 重新设置activeIndex
                that.points.forEach((item, index) => { item.activeIndex = index })

                // 上一条线链接下一个点
                let concatLine = that.lines[index - 1] ? that.lines[index - 1] : that.lines[that.lines.length - 1]
                let nextLine = that.lines[index + 1] ? that.lines[index + 1] : that.lines[0]
                concatLine.positions[1] = nextLine.positions[0]
                // 删除线  重新设置activeIndex
                that.lines[index].destroy()
                that.lines.splice(index, 1)
                that.lines.forEach((item, index) => { item.activeIndex = index })

            }
        }

    }, Cesium.ScreenSpaceEventType.RIGHT_UP)


    // 鼠标移动事件
    this.handler.setInputAction(function (e) {
        
        // 判断当前是否有活跃操作点
        if (activeIndex === null) {
            return
        }
        let position = that.earth.pickPosition({ x: e.endPosition.x, y: e.endPosition.y });
        let cartesian = Cesium.Cartesian3.fromDegrees(that.radian * position[0], that.radian * position[1], 1)
        // Cesium.Cartesian3.fromDegrees(position[0], position[1], 10)
        that.points[activeIndex].position = cartesian

        that.lines[activeIndex].positions[0] = position
        
        if (activeIndex == 0) {
            that.lines[that.lines.length - 1].positions[1] = position
        } else {
            that.lines[activeIndex - 1].positions[1] = position
        }
        
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

}

// 在多边形上添加点 并将线打断 cPosition：cesium地理坐标  position：EX地理坐标
PolygonEdit.prototype.addPoint = function (cPosition, position, index) {
    let viewer = this.viewer
    let radian = this.radian

    // 添加点
    let point = viewer.entities.add({
        position: cPosition,
        point: {
            pixelSize: 10,
            // 填充色
            color: new Cesium.Color(this.color[0], this.color[1], this.color[2], 1),
            // 是否有边框
            outline: true,
            // 边框颜色
            outlineColor: new Cesium.Color(this.outlineColor[0], this.outlineColor[1], this.outlineColor[2], 1),
            // 边框宽度
            outlineWidth: 3
        },
    });
    point.editType = 'editPoint'
    // 点重新排序
    this.points.splice(index + 1, 0, point)
    this.points.forEach((item, index) => { item.activeIndex = index })

    // 添加线段
    let startLine = this.lines[index]
    let endLine = this.lines[index - 1] ? this.lines[index - 1] : this.lines[this.lines.length - 1]
    startLine.positions[0] = position
    let polyline = new XE.Obj.Polyline(this.earth);
    polyline.ground = true
    polyline.width = 4
    polyline.material.XbsjColorMaterial.color = [ 1,1,1,1 ]
    polyline.positions = [ endLine.positions[1], position ]
    polyline.editType = 'editLine'

    // 线段重新排序
    this.lines.splice(index, 0, polyline)
    this.lines.forEach((item, index) => { item.activeIndex = index })

}

// 关闭编辑
PolygonEdit.prototype.off = function () {
    this.getPolygon()
    this.polygon.positions = this.polygonPositions
    this.polygon.show = true


    // 移除操作点
    this.points.forEach(item => {
        this.viewer.entities.remove(item)
    })
    this.points = []

    // 移除操作线
    this.lines.forEach(item => {
        item.destroy()
    })
    this.lines = []

    // 解绑事件监听
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN)
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_UP)
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_DOWN)
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_UP)
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)

}

// 获取多边形点集坐标
PolygonEdit.prototype.getPolygon = function () {
    let radian = 180 / Math.PI;
    let list = []
    let polygonPositions = []
    // 通过控制线获取多边形轮廓
    this.lines.forEach(item => {
        let position = item.positions[0]
        // 弧度坐标列表
        polygonPositions = polygonPositions.concat([
            position[0],
            position[1]
        ])
        // 地理坐标列表
        list = list.concat([
            position[0] * radian,
            position[1] * radian
        ])
    })

    this.polygonPositions = polygonPositions

    return list
}


export default PolygonEdit